[[...path]].page.tsx 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663
  1. import React, { ReactNode, useEffect } from 'react';
  2. import EventEmitter from 'events';
  3. import { isIPageInfoForEntity } from '@growi/core';
  4. import type {
  5. IDataWithMeta, IPageInfoForEntity, IPagePopulatedToShowRevision, IUserHasId,
  6. } from '@growi/core';
  7. import {
  8. isClient, pagePathUtils, pathUtils,
  9. } from '@growi/core/dist/utils';
  10. import ExtensibleCustomError from 'extensible-custom-error';
  11. import type {
  12. GetServerSideProps, GetServerSidePropsContext,
  13. } from 'next';
  14. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  15. import dynamic from 'next/dynamic';
  16. import Head from 'next/head';
  17. import { useRouter } from 'next/router';
  18. import superjson from 'superjson';
  19. import { useCurrentGrowiLayoutFluidClassName, useEditorModeClassName } from '~/client/services/layout';
  20. import { PageView } from '~/components/Page/PageView';
  21. import { DrawioViewerScript } from '~/components/Script/DrawioViewerScript'; import type { CrowiRequest } from '~/interfaces/crowi-request';
  22. import type { EditorConfig } from '~/interfaces/editor-settings';
  23. import type { IPageGrantData } from '~/interfaces/page';
  24. import type { RendererConfig } from '~/interfaces/services/renderer';
  25. import type { PageModel, PageDocument } from '~/server/models/page';
  26. import type { PageRedirectModel } from '~/server/models/page-redirect';
  27. import {
  28. useCurrentUser,
  29. useIsForbidden, useIsSharedUser,
  30. useIsEnabledStaleNotification, useIsIdenticalPath,
  31. useIsSearchServiceConfigured, useIsSearchServiceReachable, useDisableLinkSharing,
  32. useHackmdUri, useDefaultIndentSize, useIsIndentSizeForced,
  33. useIsAclEnabled, useIsSearchPage, useIsEnabledAttachTitleHeader,
  34. useCsrfToken, useIsSearchScopeChildrenAsDefault, useCurrentPathname,
  35. useIsSlackConfigured, useRendererConfig, useGrowiCloudUri,
  36. useEditorConfig, useIsAllReplyShown, useIsUploadableFile, useIsUploadableImage, useIsContainerFluid, useIsNotCreatable,
  37. } from '~/stores/context';
  38. import { useEditingMarkdown } from '~/stores/editor';
  39. import { useHasDraftOnHackmd, usePageIdOnHackmd, useRevisionIdHackmdSynced } from '~/stores/hackmd';
  40. import {
  41. useSWRxCurrentPage, useSWRMUTxCurrentPage, useSWRxIsGrantNormalized, useCurrentPageId,
  42. useIsNotFound, useIsLatestRevision, useTemplateTagData, useTemplateBodyData,
  43. } from '~/stores/page';
  44. import { useRedirectFrom } from '~/stores/page-redirect';
  45. import { useRemoteRevisionId } from '~/stores/remote-latest-page';
  46. import { useSelectedGrant } from '~/stores/ui';
  47. import { useSetupGlobalSocket, useSetupGlobalSocketForPage } from '~/stores/websocket';
  48. import loggerFactory from '~/utils/logger';
  49. import { BasicLayout } from '../components/Layout/BasicLayout';
  50. import GrowiContextualSubNavigationSubstance from '../components/Navbar/GrowiContextualSubNavigation';
  51. import { DisplaySwitcher } from '../components/Page/DisplaySwitcher';
  52. import type { NextPageWithLayout } from './_app.page';
  53. import type { CommonProps } from './utils/commons';
  54. import {
  55. getNextI18NextConfig, getServerSideCommonProps, generateCustomTitleForPage, useInitSidebarConfig, skipSSR,
  56. } from './utils/commons';
  57. declare global {
  58. // eslint-disable-next-line vars-on-top, no-var
  59. var globalEmitter: EventEmitter;
  60. }
  61. const GrowiPluginsActivator = dynamic(() => import('~/features/growi-plugin/client/components').then(mod => mod.GrowiPluginsActivator), { ssr: false });
  62. const DescendantsPageListModal = dynamic(() => import('../components/DescendantsPageListModal').then(mod => mod.DescendantsPageListModal), { ssr: false });
  63. const UnsavedAlertDialog = dynamic(() => import('../components/UnsavedAlertDialog'), { ssr: false });
  64. const DrawioModal = dynamic(() => import('../components/PageEditor/DrawioModal').then(mod => mod.DrawioModal), { ssr: false });
  65. const HandsontableModal = dynamic(() => import('../components/PageEditor/HandsontableModal').then(mod => mod.HandsontableModal), { ssr: false });
  66. const TemplateModal = dynamic(() => import('../components/TemplateModal').then(mod => mod.TemplateModal), { ssr: false });
  67. const LinkEditModal = dynamic(() => import('../components/PageEditor/LinkEditModal').then(mod => mod.LinkEditModal), { ssr: false });
  68. const PageStatusAlert = dynamic(() => import('../components/PageStatusAlert').then(mod => mod.PageStatusAlert), { ssr: false });
  69. const QuestionnaireModalManager = dynamic(() => import('~/features/questionnaire/client/components/QuestionnaireModalManager'), { ssr: false });
  70. const logger = loggerFactory('growi:pages:all');
  71. const {
  72. isPermalink: _isPermalink, isCreatablePage,
  73. } = pagePathUtils;
  74. const { removeHeadingSlash } = pathUtils;
  75. type IPageToShowRevisionWithMeta = IDataWithMeta<IPagePopulatedToShowRevision & PageDocument, IPageInfoForEntity>;
  76. type IPageToShowRevisionWithMetaSerialized = IDataWithMeta<string, string>;
  77. superjson.registerCustom<IPageToShowRevisionWithMeta, IPageToShowRevisionWithMetaSerialized>(
  78. {
  79. isApplicable: (v): v is IPageToShowRevisionWithMeta => {
  80. return v?.data != null
  81. && v?.data.toObject != null
  82. && v?.meta != null
  83. && isIPageInfoForEntity(v.meta);
  84. },
  85. serialize: (v) => {
  86. return {
  87. data: superjson.stringify(v.data.toObject()),
  88. meta: superjson.stringify(v.meta),
  89. };
  90. },
  91. deserialize: (v) => {
  92. return {
  93. data: superjson.parse(v.data),
  94. meta: v.meta != null ? superjson.parse(v.meta) : undefined,
  95. };
  96. },
  97. },
  98. 'IPageToShowRevisionWithMetaTransformer',
  99. );
  100. // GrowiContextualSubNavigation for NOT shared page
  101. type GrowiContextualSubNavigationProps = {
  102. isLinkSharingDisabled: boolean,
  103. }
  104. const GrowiContextualSubNavigation = (props: GrowiContextualSubNavigationProps): JSX.Element => {
  105. const { isLinkSharingDisabled } = props;
  106. const { data: currentPage } = useSWRxCurrentPage();
  107. return (
  108. <div data-testid="grw-contextual-sub-nav">
  109. <GrowiContextualSubNavigationSubstance currentPage={currentPage} isLinkSharingDisabled={isLinkSharingDisabled}/>
  110. </div>
  111. );
  112. };
  113. type Props = CommonProps & {
  114. pageWithMeta: IPageToShowRevisionWithMeta | null,
  115. // pageUser?: any,
  116. redirectFrom?: string;
  117. // shareLinkId?: string;
  118. isLatestRevision?: boolean,
  119. isIdenticalPathPage?: boolean,
  120. isForbidden: boolean,
  121. isNotFound: boolean,
  122. isNotCreatable: boolean,
  123. // isAbleToDeleteCompletely: boolean,
  124. templateTagData?: string[],
  125. templateBodyData?: string,
  126. isSearchServiceConfigured: boolean,
  127. isSearchServiceReachable: boolean,
  128. isSearchScopeChildrenAsDefault: boolean,
  129. isSlackConfigured: boolean,
  130. // isMailerSetup: boolean,
  131. isAclEnabled: boolean,
  132. // hasSlackConfig: boolean,
  133. drawioUri: string | null,
  134. hackmdUri: string,
  135. noCdn: string,
  136. // highlightJsStyle: string,
  137. isAllReplyShown: boolean,
  138. isContainerFluid: boolean,
  139. editorConfig: EditorConfig,
  140. isEnabledStaleNotification: boolean,
  141. isEnabledAttachTitleHeader: boolean,
  142. // isEnabledLinebreaks: boolean,
  143. // isEnabledLinebreaksInComments: boolean,
  144. adminPreferredIndentSize: number,
  145. isIndentSizeForced: boolean,
  146. disableLinkSharing: boolean,
  147. skipSSR: boolean,
  148. ssrMaxRevisionBodyLength: number,
  149. grantData?: IPageGrantData,
  150. rendererConfig: RendererConfig,
  151. };
  152. const Page: NextPageWithLayout<Props> = (props: Props) => {
  153. // register global EventEmitter
  154. if (isClient() && window.globalEmitter == null) {
  155. window.globalEmitter = new EventEmitter();
  156. }
  157. const router = useRouter();
  158. useCurrentUser(props.currentUser ?? null);
  159. // commons
  160. useEditorConfig(props.editorConfig);
  161. useCsrfToken(props.csrfToken);
  162. useGrowiCloudUri(props.growiCloudUri);
  163. // page
  164. useIsContainerFluid(props.isContainerFluid);
  165. // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
  166. useIsForbidden(props.isForbidden);
  167. useIsNotCreatable(props.isNotCreatable);
  168. useRedirectFrom(props.redirectFrom ?? null);
  169. useIsSharedUser(false); // this page cann't be routed for '/share'
  170. useIsIdenticalPath(props.isIdenticalPathPage ?? false);
  171. useIsEnabledStaleNotification(props.isEnabledStaleNotification);
  172. useIsSearchPage(false);
  173. useIsEnabledAttachTitleHeader(props.isEnabledAttachTitleHeader);
  174. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  175. useIsSearchServiceReachable(props.isSearchServiceReachable);
  176. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  177. useIsSlackConfigured(props.isSlackConfigured);
  178. // useIsMailerSetup(props.isMailerSetup);
  179. useIsAclEnabled(props.isAclEnabled);
  180. // useHasSlackConfig(props.hasSlackConfig);
  181. useHackmdUri(props.hackmdUri);
  182. // useNoCdn(props.noCdn);
  183. useDefaultIndentSize(props.adminPreferredIndentSize);
  184. useIsIndentSizeForced(props.isIndentSizeForced);
  185. useDisableLinkSharing(props.disableLinkSharing);
  186. useRendererConfig(props.rendererConfig);
  187. // useRendererSettings(props.rendererSettingsStr != null ? JSON.parse(props.rendererSettingsStr) : undefined);
  188. // useGrowiRendererConfig(props.growiRendererConfigStr != null ? JSON.parse(props.growiRendererConfigStr) : undefined);
  189. useIsAllReplyShown(props.isAllReplyShown);
  190. useIsUploadableFile(props.editorConfig.upload.isUploadableFile);
  191. useIsUploadableImage(props.editorConfig.upload.isUploadableImage);
  192. const { pageWithMeta } = props;
  193. const pageId = pageWithMeta?.data._id;
  194. const pagePath = pageWithMeta?.data.path ?? props.currentPathname;
  195. const revisionBody = pageWithMeta?.data.revision?.body;
  196. usePageIdOnHackmd(pageWithMeta?.data.pageIdOnHackmd);
  197. useHasDraftOnHackmd(pageWithMeta?.data.hasDraftOnHackmd ?? false);
  198. useCurrentPathname(props.currentPathname);
  199. useSWRxCurrentPage(pageWithMeta?.data ?? null); // store initial data
  200. const { trigger: mutateCurrentPage } = useSWRMUTxCurrentPage();
  201. const { mutate: mutateEditingMarkdown } = useEditingMarkdown();
  202. const { data: currentPageId, mutate: mutateCurrentPageId } = useCurrentPageId();
  203. const { mutate: mutateIsNotFound } = useIsNotFound();
  204. const { mutate: mutateIsLatestRevision } = useIsLatestRevision();
  205. const { data: grantData } = useSWRxIsGrantNormalized(pageId);
  206. const { mutate: mutateSelectedGrant } = useSelectedGrant();
  207. const { mutate: mutateRemoteRevisionId } = useRemoteRevisionId();
  208. const { mutate: mutateRevisionIdHackmdSynced } = useRevisionIdHackmdSynced();
  209. const { mutate: mutateTemplateTagData } = useTemplateTagData();
  210. const { mutate: mutateTemplateBodyData } = useTemplateBodyData();
  211. useSetupGlobalSocket();
  212. useSetupGlobalSocketForPage(pageId);
  213. const growiLayoutFluidClass = useCurrentGrowiLayoutFluidClassName(pageWithMeta?.data);
  214. // Store initial data (When revisionBody is not SSR)
  215. useEffect(() => {
  216. if (!props.skipSSR) {
  217. return;
  218. }
  219. if (currentPageId != null && !props.isNotFound) {
  220. const mutatePageData = async() => {
  221. const pageData = await mutateCurrentPage();
  222. mutateEditingMarkdown(pageData?.revision.body);
  223. };
  224. // If skipSSR is true, use the API to retrieve page data.
  225. // Because pageWIthMeta does not contain revision.body
  226. mutatePageData();
  227. }
  228. }, [currentPageId, mutateCurrentPage, mutateEditingMarkdown, props.isNotFound, props.skipSSR]);
  229. // sync grant data
  230. useEffect(() => {
  231. const grantDataToApply = props.grantData ? props.grantData : grantData?.grantData.currentPageGrant;
  232. mutateSelectedGrant(grantDataToApply);
  233. }, [grantData?.grantData.currentPageGrant, mutateSelectedGrant, props.grantData]);
  234. // sync pathname by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
  235. useEffect(() => {
  236. const decodedURI = decodeURI(window.location.pathname);
  237. if (isClient() && decodedURI !== props.currentPathname) {
  238. const { search, hash } = window.location;
  239. router.replace(`${props.currentPathname}${search}${hash}`, undefined, { shallow: true });
  240. }
  241. }, [props.currentPathname, router]);
  242. // initialize mutateEditingMarkdown only once per page
  243. // need to include useCurrentPathname not useCurrentPagePath
  244. useEffect(() => {
  245. if (props.currentPathname != null) {
  246. mutateEditingMarkdown(revisionBody);
  247. }
  248. }, [mutateEditingMarkdown, revisionBody, props.currentPathname]);
  249. useEffect(() => {
  250. mutateRemoteRevisionId(pageWithMeta?.data.revision?._id);
  251. mutateRevisionIdHackmdSynced(pageWithMeta?.data.revisionHackmdSynced);
  252. }, [mutateRemoteRevisionId, mutateRevisionIdHackmdSynced, pageWithMeta?.data.revision?._id, pageWithMeta?.data.revisionHackmdSynced]);
  253. useEffect(() => {
  254. mutateCurrentPageId(pageId ?? null);
  255. }, [mutateCurrentPageId, pageId]);
  256. useEffect(() => {
  257. mutateIsNotFound(props.isNotFound);
  258. }, [mutateIsNotFound, props.isNotFound]);
  259. useEffect(() => {
  260. mutateIsLatestRevision(props.isLatestRevision);
  261. }, [mutateIsLatestRevision, props.isLatestRevision]);
  262. useEffect(() => {
  263. mutateTemplateTagData(props.templateTagData);
  264. }, [props.templateTagData, mutateTemplateTagData]);
  265. useEffect(() => {
  266. mutateTemplateBodyData(props.templateBodyData);
  267. }, [props.templateBodyData, mutateTemplateBodyData]);
  268. const title = generateCustomTitleForPage(props, pagePath);
  269. return (
  270. <>
  271. <Head>
  272. <title>{title}</title>
  273. </Head>
  274. <div className={`dynamic-layout-root ${growiLayoutFluidClass} h-100 d-flex flex-column justify-content-between`}>
  275. <header className="py-0 position-relative">
  276. <div id="grw-subnav-container">
  277. <GrowiContextualSubNavigation isLinkSharingDisabled={props.disableLinkSharing} />
  278. </div>
  279. </header>
  280. <div id="grw-subnav-sticky-trigger" className="sticky-top"></div>
  281. <div id="grw-fav-sticky-trigger" className="sticky-top"></div>
  282. <DisplaySwitcher
  283. pageView={
  284. <PageView
  285. pagePath={pagePath}
  286. initialPage={pageWithMeta?.data}
  287. rendererConfig={props.rendererConfig}
  288. />
  289. }
  290. />
  291. <PageStatusAlert />
  292. </div>
  293. </>
  294. );
  295. };
  296. type LayoutProps = Props & {
  297. children?: ReactNode
  298. }
  299. const Layout = ({ children, ...props }: LayoutProps): JSX.Element => {
  300. const className = useEditorModeClassName();
  301. // init sidebar config with UserUISettings and sidebarConfig
  302. useInitSidebarConfig(props.sidebarConfig, props.userUISettings);
  303. return (
  304. <BasicLayout className={className}>
  305. {children}
  306. </BasicLayout>
  307. );
  308. };
  309. Page.getLayout = function getLayout(page: React.ReactElement<Props>) {
  310. return (
  311. <>
  312. <GrowiPluginsActivator />
  313. <DrawioViewerScript />
  314. <Layout {...page.props}>
  315. {page}
  316. </Layout>
  317. <UnsavedAlertDialog />
  318. <DescendantsPageListModal />
  319. <DrawioModal />
  320. <HandsontableModal />
  321. <QuestionnaireModalManager />
  322. <TemplateModal />
  323. <LinkEditModal />
  324. </>
  325. );
  326. };
  327. function getPageIdFromPathname(currentPathname: string): string | null {
  328. return _isPermalink(currentPathname) ? removeHeadingSlash(currentPathname) : null;
  329. }
  330. class MultiplePagesHitsError extends ExtensibleCustomError {
  331. pagePath: string;
  332. constructor(pagePath: string) {
  333. super(`MultiplePagesHitsError occured by '${pagePath}'`);
  334. this.pagePath = pagePath;
  335. }
  336. }
  337. // apply parent page grant fot creating page
  338. async function applyGrantToPage(props: Props, ancestor: any) {
  339. await ancestor.populate('grantedGroup');
  340. const grant = {
  341. grant: ancestor.grant,
  342. };
  343. const grantedGroup = ancestor.grantedGroup ? {
  344. grantedGroup: {
  345. id: ancestor.grantedGroup.id,
  346. name: ancestor.grantedGroup.name,
  347. },
  348. } : {};
  349. props.grantData = Object.assign(grant, grantedGroup);
  350. }
  351. async function injectPageData(context: GetServerSidePropsContext, props: Props): Promise<void> {
  352. const { model: mongooseModel } = await import('mongoose');
  353. const req: CrowiRequest = context.req as CrowiRequest;
  354. const { crowi } = req;
  355. const { revisionId } = req.query;
  356. const Page = crowi.model('Page') as PageModel;
  357. const PageRedirect = mongooseModel('PageRedirect') as PageRedirectModel;
  358. const { pageService, configManager } = crowi;
  359. let currentPathname = props.currentPathname;
  360. const pageId = getPageIdFromPathname(currentPathname);
  361. const isPermalink = _isPermalink(currentPathname);
  362. const { user } = req;
  363. if (!isPermalink) {
  364. // check redirects
  365. const chains = await PageRedirect.retrievePageRedirectEndpoints(currentPathname);
  366. if (chains != null) {
  367. // overwrite currentPathname
  368. currentPathname = chains.end.toPath;
  369. props.currentPathname = currentPathname;
  370. // set redirectFrom
  371. props.redirectFrom = chains.start.fromPath;
  372. }
  373. // check whether the specified page path hits to multiple pages
  374. const count = await Page.countByPathAndViewer(currentPathname, user, null, true);
  375. if (count > 1) {
  376. throw new MultiplePagesHitsError(currentPathname);
  377. }
  378. }
  379. const pageWithMeta: IPageToShowRevisionWithMeta | null = await pageService.findPageAndMetaDataByViewer(pageId, currentPathname, user, true); // includeEmpty = true, isSharedPage = false
  380. const page = pageWithMeta?.data as unknown as PageDocument;
  381. // add user to seen users
  382. if (page != null && user != null) {
  383. await page.seen(user);
  384. }
  385. // populate & check if the revision is latest
  386. if (page != null) {
  387. page.initLatestRevisionField(revisionId);
  388. props.isLatestRevision = page.isLatestRevision();
  389. const ssrMaxRevisionBodyLength = configManager.getConfig('crowi', 'app:ssrMaxRevisionBodyLength');
  390. props.skipSSR = await skipSSR(page, ssrMaxRevisionBodyLength);
  391. await page.populateDataToShowRevision(props.skipSSR); // shouldExcludeBody = skipSSR
  392. }
  393. if (page == null && user != null) {
  394. const templateData = await Page.findTemplate(props.currentPathname);
  395. if (templateData != null) {
  396. props.templateTagData = templateData.templateTags as string[];
  397. props.templateBodyData = templateData.templateBody as string;
  398. }
  399. // apply pagrent page grant
  400. const ancestor = await Page.findAncestorByPathAndViewer(currentPathname, user);
  401. if (ancestor != null) {
  402. await applyGrantToPage(props, ancestor);
  403. }
  404. }
  405. props.pageWithMeta = pageWithMeta;
  406. }
  407. async function injectRoutingInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  408. const req: CrowiRequest = context.req as CrowiRequest;
  409. const { crowi } = req;
  410. const Page = crowi.model('Page') as PageModel;
  411. const { currentPathname } = props;
  412. const pageId = getPageIdFromPathname(currentPathname);
  413. const isPermalink = _isPermalink(currentPathname);
  414. const page = props.pageWithMeta?.data;
  415. if (props.isIdenticalPathPage) {
  416. props.isNotCreatable = true;
  417. }
  418. else if (page == null) {
  419. props.isNotFound = true;
  420. props.isNotCreatable = !isCreatablePage(currentPathname);
  421. // check the page is forbidden or just does not exist.
  422. const count = isPermalink ? await Page.count({ _id: pageId }) : await Page.count({ path: currentPathname });
  423. props.isForbidden = count > 0;
  424. }
  425. else {
  426. props.isNotFound = page.isEmpty;
  427. props.isNotCreatable = false;
  428. props.isForbidden = false;
  429. // /62a88db47fed8b2d94f30000 ==> /path/to/page
  430. if (isPermalink && page.isEmpty) {
  431. props.currentPathname = page.path;
  432. }
  433. // /path/to/page ==> /62a88db47fed8b2d94f30000
  434. if (!isPermalink && !page.isEmpty) {
  435. const isToppage = pagePathUtils.isTopPage(props.currentPathname);
  436. if (!isToppage) {
  437. props.currentPathname = `/${page._id}`;
  438. }
  439. }
  440. }
  441. }
  442. // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  443. // const req: CrowiRequest = context.req as CrowiRequest;
  444. // const { crowi } = req;
  445. // const UserModel = crowi.model('User');
  446. // if (isUserPage(props.currentPagePath)) {
  447. // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
  448. // if (user != null) {
  449. // props.pageUser = JSON.stringify(user.toObject());
  450. // }
  451. // }
  452. // }
  453. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  454. const req: CrowiRequest = context.req as CrowiRequest;
  455. const { crowi } = req;
  456. const {
  457. searchService, configManager, aclService,
  458. } = crowi;
  459. props.isSearchServiceConfigured = searchService.isConfigured;
  460. props.isSearchServiceReachable = searchService.isReachable;
  461. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  462. props.isSlackConfigured = crowi.slackIntegrationService.isSlackConfigured;
  463. // props.isMailerSetup = mailService.isMailerSetup;
  464. props.isAclEnabled = aclService.isAclEnabled();
  465. // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
  466. props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  467. props.hackmdUri = configManager.getConfig('crowi', 'app:hackmdUri');
  468. props.noCdn = configManager.getConfig('crowi', 'app:noCdn');
  469. // props.highlightJsStyle = configManager.getConfig('crowi', 'customize:highlightJsStyle');
  470. props.isAllReplyShown = configManager.getConfig('crowi', 'customize:isAllReplyShown');
  471. props.isContainerFluid = configManager.getConfig('crowi', 'customize:isContainerFluid');
  472. props.isEnabledStaleNotification = configManager.getConfig('crowi', 'customize:isEnabledStaleNotification');
  473. props.disableLinkSharing = configManager.getConfig('crowi', 'security:disableLinkSharing');
  474. props.editorConfig = {
  475. upload: {
  476. isUploadableFile: crowi.fileUploadService.getFileUploadEnabled(),
  477. isUploadableImage: crowi.fileUploadService.getIsUploadable(),
  478. },
  479. };
  480. props.adminPreferredIndentSize = configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize');
  481. props.isIndentSizeForced = configManager.getConfig('markdown', 'markdown:isIndentSizeForced');
  482. props.isEnabledAttachTitleHeader = configManager.getConfig('crowi', 'customize:isEnabledAttachTitleHeader');
  483. props.rendererConfig = {
  484. isEnabledLinebreaks: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks'),
  485. isEnabledLinebreaksInComments: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments'),
  486. adminPreferredIndentSize: configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize'),
  487. isIndentSizeForced: configManager.getConfig('markdown', 'markdown:isIndentSizeForced'),
  488. drawioUri: configManager.getConfig('crowi', 'app:drawioUri'),
  489. plantumlUri: configManager.getConfig('crowi', 'app:plantumlUri'),
  490. // XSS Options
  491. isEnabledXssPrevention: configManager.getConfig('markdown', 'markdown:rehypeSanitize:isEnabledPrevention'),
  492. xssOption: configManager.getConfig('markdown', 'markdown:rehypeSanitize:option'),
  493. attrWhitelist: JSON.parse(crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:attributes')),
  494. tagWhitelist: crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:tagNames'),
  495. highlightJsStyleBorder: crowi.configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
  496. };
  497. props.ssrMaxRevisionBodyLength = configManager.getConfig('crowi', 'app:ssrMaxRevisionBodyLength');
  498. }
  499. /**
  500. * for Server Side Translations
  501. * @param context
  502. * @param props
  503. * @param namespacesRequired
  504. */
  505. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  506. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  507. props._nextI18Next = nextI18NextConfig._nextI18Next;
  508. }
  509. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  510. const req = context.req as CrowiRequest<IUserHasId & any>;
  511. const { user } = req;
  512. const result = await getServerSideCommonProps(context);
  513. // check for presence
  514. // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
  515. if (!('props' in result)) {
  516. throw new Error('invalid getSSP result');
  517. }
  518. const props: Props = result.props as Props;
  519. if (props.redirectDestination != null) {
  520. return {
  521. redirect: {
  522. permanent: false,
  523. destination: props.redirectDestination,
  524. },
  525. };
  526. }
  527. if (user != null) {
  528. props.currentUser = user.toObject();
  529. }
  530. try {
  531. await injectPageData(context, props);
  532. }
  533. catch (err) {
  534. if (err instanceof MultiplePagesHitsError) {
  535. props.isIdenticalPathPage = true;
  536. }
  537. else {
  538. throw err;
  539. }
  540. }
  541. await injectRoutingInformation(context, props);
  542. injectServerConfigurations(context, props);
  543. await injectNextI18NextConfigurations(context, props, ['translation']);
  544. return {
  545. props,
  546. };
  547. };
  548. export default Page;